<template>
  <s-layout
    navbar="custom"
    tabbar="/pages/index/sale"
  >
    <view class="page-container">
      <!-- 头部标题 -->
      <view class="page-title">
        <text class="title-text">选择车型</text>
      </view>

      <!-- 头部区域 - 搜索框 -->
      <view class="header-section">
        <view class="search-container">
          <s-search-block
            :data="{ placeholder: '搜索车型', borderRadius: 18 }"
            :radius="18"
            elBackground="#f5f6f8"
            :height="36"
            width="100%"
            :navbar="false"
            @click="onSearchClick"
          />
        </view>
      </view>

      <!-- 主体内容 -->
      <view class="main-content">
        <!-- 左侧分类 -->
        <view class="category-sidebar">
          <scroll-view scroll-y="true" class="category-scroll">
            <view
              v-for="(category, index) in state.categories"
              :key="category.id"
              class="category-item"
              :class="{ 'active': index === state.activeCategory }"
              @tap="selectCategory(index)"
            >
              <text class="category-name">{{ category.name }}</text>
            </view>
          </scroll-view>
        </view>

        <!-- 右侧车辆列表 -->
        <view class="car-content">
          <scroll-view scroll-y="true" class="car-list" @scrolltolower="loadMore">
            <!-- 空状态显示 -->
            <view v-if="state.carList.length === 0 && state.loadStatus !== 'loading'" class="empty-category">
              <view class="empty-content">
                <view class="empty-line"></view>
                <text class="empty-text">{{ state.categories[state.activeCategory]?.name || '暂无数据' }}</text>
                <view class="empty-line"></view>
              </view>
            </view>

            <!-- 车辆列表 -->
            <view
              v-for="car in sortedCarList"
              :key="car.id"
              class="car-item"
              @tap="selectCar(car)"
            >
              <image class="car-image" :src="car.image" mode="aspectFit" />
              <view class="car-info">
                <text class="car-name">{{ car.name }}</text>
                <view class="car-price-section">
                  <text v-if="car.price" class="car-price">{{ car.price }}</text>
                </view>
              </view>
            </view>

            <!-- 加载状态 -->
            <view v-if="state.loadStatus === 'loading'" class="loading-text">加载中...</view>
            <view v-if="state.loadStatus === 'error'" class="loading-text">加载失败</view>

            <view class="bottom-safe-area"></view>
          </scroll-view>
        </view>
      </view>
    </view>
  </s-layout>
</template>

<script setup>
import { reactive, computed, onMounted } from 'vue';
import sheep from '@/sheep';
import CategoryApi from '@/sheep/api/product/category';
import SpuApi from '@/sheep/api/product/spu';

// 隐藏原生tabBar
uni.hideTabBar({
  fail: () => {},
});

const state = reactive({
  activeCategory: 0,
  categories: [
    { id: 0, name: '全部', type: 'all' }
  ],
  carList: [],
  loadStatus: '',
  pagination: {
    pageNo: 1,
    pageSize: 20,
    total: 0
  },
  vehicleSaleCategoryId: null, // 存储车辆售卖父分类ID
  allSubCategoryIds: [] // 存储所有子分类ID
});

// 获取分类数据
async function getCategoryList() {
  try {
    const { data } = await CategoryApi.getCategoryList();

    // 找到车辆售卖的一级分类
    const vehicleSaleCategory = data.find(item => item.name === '车辆售卖' && item.parentId === 0);

    if (vehicleSaleCategory) {
      // 存储车辆售卖父分类ID
      state.vehicleSaleCategoryId = vehicleSaleCategory.id;

      // 过滤出车辆售卖的二级分类
      const subCategories = data.filter(item => item.parentId === vehicleSaleCategory.id);

      // 存储所有子分类ID
      state.allSubCategoryIds = subCategories.map(item => item.id);

      // 构建分类数据，保留全部选项
      const categoryList = [
        { id: 0, name: '全部', type: 'all' },
        ...subCategories.map(item => ({
          id: item.id,
          name: item.name,
          type: item.name.toLowerCase(),
          picUrl: item.picUrl
        }))
      ];

      state.categories = categoryList;
      // 获取分类数据后，加载商品列表
      getCarList();
    }
  } catch (error) {
    console.error('获取分类失败:', error);
  }
}

// 获取车辆列表
async function getCarList() {
  try {
    state.loadStatus = 'loading';

    const selectedCategory = state.categories[state.activeCategory];
    const params = {
      pageNo: state.pagination.pageNo,
      pageSize: state.pagination.pageSize,
    };

    // 根据选中分类设置查询参数
    if (selectedCategory.type === 'all') {
      // 点击全部时，传递所有子分类ID
      if (state.allSubCategoryIds.length > 0) {
        params.categoryIds = state.allSubCategoryIds.join(',');
      }
    } else {
      // 点击具体分类时，传递单个分类ID
      params.categoryId = selectedCategory.id;
    }

    const { code, data } = await SpuApi.getSpuPage(params);

    if (code === 0) {
      // 处理数据格式，映射到车辆列表格式
      const processedList = data.list.map(item => ({
        id: item.id,
        name: item.name,
        price: `¥${(item.price / 100).toFixed(0)}/台`, // 价格从分转换为元，添加"/台"单位
        priceValue: item.price / 100,
        image: item.picUrl,
        categoryId: item.categoryId
      }));

      if (state.pagination.pageNo === 1) {
        state.carList = processedList;
      } else {
        state.carList = [...state.carList, ...processedList];
      }

      state.pagination.total = data.total;
      state.loadStatus = state.carList.length < data.total ? 'more' : 'noMore';
    } else {
      state.loadStatus = 'error';
    }
  } catch (error) {
    console.error('获取车辆列表失败:', error);
    state.loadStatus = 'error';
  }
}

onMounted(() => {
  getCategoryList();
});

// 根据排序方式排序车辆列表
const sortedCarList = computed(() => {
  return state.carList;
});

function selectCategory(index) {
  state.activeCategory = index;
  // 重置分页
  state.pagination.pageNo = 1;
  state.carList = [];
  // 重新加载数据
  getCarList();
}

function selectCar(car) {
  console.log('选择车辆:', car);
  // 跳转到售卖商品详情页
  sheep.$router.go('/pages/goods/sale', { id: car.id });
}

// 搜索框点击事件
function onSearchClick() {
  sheep.$router.go('/pages/index/search');
}

// 加载更多
function loadMore() {
  if (state.loadStatus === 'more') {
    state.pagination.pageNo++;
    getCarList();
  }
}
</script>

<style lang="scss" scoped>
.page-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #fff;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
}

/* 页面标题 */
.page-title {
  padding: 24rpx 30rpx 16rpx;
  background: #fff;
  text-align: center;

  .title-text {
    font-size: 32rpx;
    color: #333;
    font-weight: 500;
    line-height: 1.4;
  }
}

/* 头部区域 - 搜索框 */
.header-section {
  display: flex;
  align-items: flex-start;
  padding: 20rpx 30rpx;
  background: #fff;
  border-bottom: 1rpx solid #f0f0f0;

  .search-container {
    flex: 1;
  }
}

.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.category-sidebar {
  width: 200rpx;
  background: #f6f6f6;
  border-right: 1rpx solid #e5e5e5;

  .category-scroll {
    height: 100%;
  }

  .category-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 32rpx 20rpx;
    border-bottom: 1rpx solid #e5e5e5;
    position: relative;

    .category-name {
      font-size: 26rpx;
      color: #666666;
      text-align: center;
      line-height: 1.4;
    }

    &.active {
      background: #fff;

      .category-name {
        color: #D4AF37;
        font-weight: 500;
      }

      &::after {
        content: '';
        position: absolute;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 6rpx;
        height: 40rpx;
        background: #D4AF37;
        border-radius: 3rpx 0 0 3rpx;
      }
    }
  }
}

.car-content {
  flex: 1;
  background: #fff;

  .car-list {
    height: 100%;
  }

  .empty-category {
    height: 400rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    .empty-content {
      display: flex;
      align-items: center;
      justify-content: center;

      .empty-line {
        width: 30rpx;
        height: 2rpx;
        background: #e5e5e5;
      }

      .empty-text {
        font-size: 28rpx;
        color: #999;
        margin: 0 20rpx;
      }
    }
  }

  .car-item {
    display: flex;
    align-items: center;
    padding: 32rpx 30rpx;
    border-bottom: 1rpx solid #f5f5f5;

    &:active {
      background: #f8f8f8;
    }

    .car-image {
      width: 160rpx;
      height: 100rpx;
      border-radius: 12rpx;
      margin-right: 24rpx;
      background-color: #f5f5f5;
    }

    .car-info {
      flex: 1;

      .car-name {
        font-size: 32rpx;
        color: #333;
        font-weight: 500;
        line-height: 1.4;
        margin-bottom: 16rpx;
      }

      .car-price-section {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 12rpx;

        .car-price {
          font-size: 28rpx;
          color: #D4AF37;
          font-weight: 500;
        }
      }
    }
  }

  .loading-text {
    text-align: center;
    padding: 40rpx 0;
    color: #999;
    font-size: 26rpx;
  }

  .bottom-safe-area {
    height: 120rpx;
  }
}

/* 响应式调整 */
@media screen and (max-width: 750rpx) {
  .category-sidebar {
    width: 160rpx;
  }

  .car-item {
    .car-image {
      width: 140rpx;
      height: 105rpx;
    }

    .car-info {
      .car-name {
        font-size: 28rpx;
      }

      .car-price {
        font-size: 30rpx;
      }
    }
  }
}
</style>
